package com.example.seh.home.secondhand;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.seh.R;
import com.example.seh.home.OrderDTO;
import com.example.seh.home.pay.PayActivity;
import com.example.seh.util.ImgUtil;
import com.example.seh.util.MyMathUtil;
import com.example.seh.util.UserMsg;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class GoodsBuyActivity extends AppCompatActivity {
    private TextView receiverName, goodsName, goodsPrice, allPrice, sendAddress;
    private EditText receiverAddress;
    private Button decrease, add, submit, chooseAddress;
    private GoodsDTO goods;
    private ImageView goodsImg;
    private Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    goodsImg.setImageBitmap((Bitmap) msg.obj);
                    break;
            }
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_buy);
        getViews();
        getActivityDatas();
        setListeners();
    }

    private void getActivityDatas() {
        Intent intent = getIntent();
        goods = (GoodsDTO) intent.getSerializableExtra("goods");
        Log.e("buy",goods.toString());
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (goods.getGoodsPic() != null) {
                    List<String> imgs = Arrays.asList(goods.getGoodsPic().split(";"));
                    try {
                        Bitmap bitmap = ImgUtil.stringToBitmap(imgs.get(0));
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = bitmap;
                        handler.sendMessage(msg);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    goodsImg.setImageResource(R.drawable.wtp);
                }
            }
        }).start();


        receiverName.setText(UserMsg.userDTO.getUsername());
        if (UserMsg.goodsBuyAddress.size() != 0) {
            receiverAddress.setText(UserMsg.goodsBuyAddress.get(0));
        }
        goodsName.setText(goods.getGoodsName());
//        goodsPrice.setText(goods.getGoodsPrice() + "");
        allPrice.setText(goods.getGoodsPrice() + "");
        sendAddress.setText(goods.getAddressName());
    }

    private void setReceiverAddress() {
        Log.e("buyaddress", UserMsg.goodsBuyAddress.size() + "");
        String[] items = (String[])UserMsg.goodsBuyAddress.toArray(new String[UserMsg.goodsBuyAddress.size()]);
        final String[] address = {""};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle("选择你的收货地址");
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                receiverAddress.setText(address[0]);
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {}
        });
        alertBuilder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                address[0] = items[i];
            }
        });
        alertBuilder.create().show();
    }


    private void setListeners() {
//        buyCount.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                Log.e("txt",s + "");
//                if (!"".equals(s + "")) {
//                    int num = Integer.parseInt(s + "");
//                    allPrice.setText(MyMathUtil.getNum(goods.getGoodsPrice() * num) + "");
//                }
//            }
//            @Override
//            public void afterTextChanged(Editable s) {
//
//            }
//        });
//        decrease.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (!"".equals(buyCount.getText().toString())){
//                    int num = Integer.parseInt(buyCount.getText().toString());
//                    if (num > 1) {
//                        num--;
//                        buyCount.setText(num + "");
//                        allPrice.setText(MyMathUtil.getNum(goods.getGoodsPrice() * num) + "");
//                    }else {
//                        Toast.makeText(getApplicationContext(), "数量至少为1", Toast.LENGTH_SHORT).show();
//                    }
//                }else {
//                    buyCount.setText("1");
//                }
//
//            }
//        });
//        add.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (!"".equals(buyCount.getText().toString())){
//                    int num = Integer.parseInt(buyCount.getText().toString());
//                    num++;
//                    buyCount.setText(num + "");
//                    allPrice.setText(MyMathUtil.getNum(goods.getGoodsPrice() * num) + "");
//                }else {
//                    buyCount.setText("1");
//                }
//
//            }
//        });
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (receiverAddress.getText().toString().trim().length() != 0) {
                    double payCount = Double.parseDouble(allPrice.getText().toString());
                    Log.e("pay", payCount + "");
                    Intent intent = new Intent(GoodsBuyActivity.this, PayActivity.class);
//                intent.putExtra("buyerId", UserMsg.userDTO.getUserId() + "");
//                intent.putExtra("sellerId", goods.getUserDTO().getUserId() + "");
//                intent.putExtra("goodsId", goods.getGoodsId());
//                intent.putExtra("price", payCount + "");

                    OrderDTO orderDTO = new OrderDTO();
                    orderDTO.setUserId(UserMsg.userDTO.getUserId());//买家id（我）
                    orderDTO.setSellerId(goods.getUserDTO().getUserId());//卖家id
                    orderDTO.setGoodsId(goods.getGoodsId());//商品id
                    orderDTO.setOrderPrice(payCount);//价格
                    orderDTO.setReceiveAddress(receiverAddress.getText().toString());//收货地址
                    orderDTO.setAddress(sendAddress.getText().toString());//发货地址
                    intent.putExtra("order", orderDTO);
                    startActivity(intent);
                } else {
                    Toast.makeText(getApplicationContext(), "请选择你的地址", Toast.LENGTH_SHORT).show();
                }

            }
        });
        chooseAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setReceiverAddress();
            }
        });
    }
//
//    private boolean verifyNum() {
//        if ("".equals(buyCount.getText().toString())) {
//            Toast.makeText(getApplicationContext(), "数量不能为空", Toast.LENGTH_SHORT).show();
//            return false;
//        }else {
//            if (Integer.parseInt(buyCount.getText().toString()) < 1){
//                Toast.makeText(getApplicationContext(), "数量至少为1", Toast.LENGTH_SHORT).show();
//                return false;
//            }
//        }
//        return true;
//    }

    private void getViews() {
        receiverName = findViewById(R.id.receiver_name);
        receiverAddress = findViewById(R.id.receiver_address);
        goodsName = findViewById(R.id.goods_buy_name);
//        goodsPrice = findViewById(R.id.goods_buy_price);
        allPrice = findViewById(R.id.goods_buy_all_price);
        sendAddress = findViewById(R.id.send_buy_address);
//        buyCount = findViewById(R.id.goods_buy_count);
//        decrease = findViewById(R.id.goods_buy_decrease);
//        add = findViewById(R.id.goods_buy_add);
        submit = findViewById(R.id.goods_buy_submit);
        goodsImg = findViewById(R.id.goods_buy_img);
        chooseAddress = findViewById(R.id.goods_buy_choose_address);
    }


}